<?php

namespace common\widgets;

use Yii;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use metronic\ToastAsset;

/**
 * Toast widget extends the [[BsAlert]] widget with an easier configuration and additional styling options including auto fade out.
 *
 * @author emhome<emhome@163.com>
 * @since 1.0
 */
class Toast extends \yii\bootstrap\Widget {

    /**
     * information alert
     */
    const TYPE_INFO = 'info';

    /**
     * danger/error alert
     */
    const TYPE_ERROR = 'error';

    /**
     * success alert
     */
    const TYPE_SUCCESS = 'success';

    /**
     * warning alert
     */
    const TYPE_WARNING = 'warning';

    /**
     * @var string the type of the alert to be displayed. One of the `TYPE_` constants. Defaults to [[TYPE_INFO]].
     */
    public $type = self::TYPE_INFO;

    /**
     * @var mixed the body content in the alert component. Note that anything between
     * the [[begin()]] and [[end()]] calls of the Alert widget will also be treated
     * as the body content, and will be rendered before this.
     */
    public $body;

    /**
     * @var integer the delay in microseconds after which the alert will be displayed. Will be useful when multiple
     * alerts are to be shown.
     */
    public $delay;

    /**
     * @var integer the delay in microseconds after which the alert will be displayed. Will be useful when multiple
     * alerts are to be shown.
     */
    private $_content;

    /**
     * Initializes the widget.
     */
    public function init() {
        parent::init();
        $title = Yii::t('message', 'Toast' . ucfirst($this->type));
        $body = Yii::t('yii', '(no set)');
        if (is_array($this->body)) {
            $title = ArrayHelper::remove($this->body, 'title', $title);
            $body = ArrayHelper::remove($this->body, 'body', $body);
        } elseif (is_string($this->body)) {
            $body = $this->body;
        }
        $type = $this->type;
        $this->_content = compact('type', 'title', 'body');
    }

    /**
     * Renders the widget.
     */
    public function run() {
        $view = $this->getView();
        ToastAsset::register($view);
        $js = 'UIToastr.init(' . Json::htmlEncode($this->_content) . ');';
        $view->registerJs($js);
    }

}
